<?php
require_once dirname(__FILE__) . "/../config/constants.php";
require_once dirname(__FILE__) . "/../config/methods.php";
require_once dirname(__FILE__) . "/../config/global.function.php";

header("Content-type: application/json; charset=utf-8");
global $output;

$method = $_REQUEST["method"];

switch($method){
    case FM_GET_CURRENT_PHOTOS:
        getCurrentPhotos();
        break;
    case FM_GET_PHOTOS_BY_DATE:
        getPhotosByDate();
        break;
    case FM_GET_PHOTOS_BY_DATE_RANGE:
        getPhotosByDateRange();
        break;
    case FM_IMPRESSION_INCR:
        incrImpression();
        break;
    default:
        empty_output();
        break;
}

/**
 * Render today's photo to client
 */
function getCurrentPhotos($isoutput=false){
    $date = new DateTime("now");
    $ndate = $date->sub(new DateInterval("P1D"));

    $result = null;
    $key = REDIS_KEY_PREFIX. $ndate->format("Y-m-d");
    $content = getRedisContentByKey($key);
    if($content){
        $result = json_decode($content);
    }else{
        $ch = curl_init();
        $opts = array(
            CURLOPT_URL=>BING_IMAGE_FETCH_URL . "?" . "date=".$ndate->format("Y-m-d"),
            CURLOPT_HTTPHEADER=>array(FM_AUTH_HEADER.": ".FM_AUTH_TOKEN),
            CURLOPT_RETURNTRANSFER=>TRUE
        );
        curl_setopt_array($ch, $opts);
        $result = curl_exec($ch);
        curl_close($ch);
        if($result){
            setRedisContentByKey($key, $result);
            $result = json_decode($result);
            initImpressionKeys($result);
        }else{
            $result = array();
        }
    }
    //$country = $_REQUEST["region"];
    $output["output"] = $result;
    if($isoutput)
        return $output;
    echo json_encode($output);
}

function initImpressionKeys($result){
    foreach($result as $one){
        $key = REDIS_KEY_PREFIX . "impressions:" . $one->key;
        setRedisContentByKey($key, 0);
    }
}

function getPhotosByDate($isoutput=false){
    $date = $_REQUEST["date"];
    if($date){
        list($year, $month, $day) = explode("-", $date);
        if(isset($year) && isset($month) && isset($day)){
            $newDate = new DateTime($year."-".$month."-".$day);
            $today = new DateTime("now");
            $interval = $today->diff($newDate);
            $days = intval($interval->format("%R%a"));
            if($days>0){
                $output["output"] = array();
            }else{
                
            }
        }
    }else{
        if($isoutput)
            return array();
        $output["output"] = array();

        echo json_encode($output);
    }

}

function getPhotosByDateRange(){
    
}

function incrImpression(){
    $key = $_REQUEST["key"];
    $redis = getRedis();
    if($redis){
        $key = REDIS_KEY_PREFIX . "impressions:". $key;
        $redis->incr($key);
    }
    echo "OK";
}

?>
